package com.cloud.wms.ui.inside.presenter;

import android.text.TextUtils;

import com.annimon.stream.Stream;
import com.cloud.core.base.BaseRxPresenter;
import com.cloud.core.utils.MessageCreator;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.http.Params;
import com.cloud.wms.http.observer.CheckNullFunc;
import com.cloud.wms.http.observer.LoadingObserver;
import com.cloud.wms.http.observer.ResponseWrapper;
import com.cloud.wms.tools.RxUtils;
import com.cloud.wms.ui.inside.contract.ReplenishUpContract;
import com.cloud.wms.ui.inside.entity.ReplenishBindEntity;
import com.cloud.wms.ui.inside.entity.ReplenishCommodityEntity;
import com.cloud.wms.ui.main.entity.BatchEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Created by FC on 2021/3/12.
 * Desc：补货下架
 */
public class ReplenishUpPresenter extends BaseRxPresenter<ReplenishUpContract.View> implements ReplenishUpContract.Presenter {

    public static final int REPLENISH_COMMODITY = 0x102;

    public static final int REPLENISH_COMPLETE = 0x107;

    public static final int REPLENISH_DETAIL = 0x105;

    public static final int CHECK_BIND_CONTAINER = 0x103;

    public static final int JUMP_TO_UP = 0x104;

    public static final int TASK = 0x108;

    public static final int REPLENISH_UP = 0x109;

    public static final int REPLENISH_UP_COMPLETE = 0x110;


    @Inject
    public ReplenishUpPresenter() {

    }

    @Override
    public void checkBindContainer(long replenishId) {
        Params params = new Params();
        params.put("BillID", replenishId);

        FineExApplication
                .component()
                .http()
                .replenishCheckBind(params)
                .map(new ResponseWrapper<>())
                .map(new CheckNullFunc<ReplenishBindEntity>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ReplenishBindEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ReplenishBindEntity info) {
                        if (info.getContainerID() > 0 || !TextUtils.isEmpty(info.getContainerCode())) {
                            mView.showContent();
                            mView.onSuccess(MessageCreator.createMessage(info, CHECK_BIND_CONTAINER));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, JUMP_TO_UP));
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                        mView.showError();
                    }
                });
    }

    @Override
    public void loadReplenishCommodity(long replenishId) {
        Params params = Params.newInstance(Params.Type.WAREHOUSE);
        params.put("BillID", replenishId);
        params.put("QueryType", 2);

        FineExApplication.component().http()
                .loadReplenishDownCommodity(params)
                .map(new ResponseWrapper<>())
                .map(commodityEntities -> (ArrayList<ReplenishCommodityEntity>) Stream.of(commodityEntities)
                        .sortBy(ReplenishCommodityEntity::getDestPosCode)
                        .toList())
                .flatMap((Function<ArrayList<ReplenishCommodityEntity>, ObservableSource<ReplenishCommodityEntity>>) Observable::fromIterable)
                .filter(commodityEntity -> !commodityEntity.isUpStatus())
                .toList()
                .toObservable()
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<List<ReplenishCommodityEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(List<ReplenishCommodityEntity> info) {
                        if (info == null || info.isEmpty()) {
                            mView.onSuccess(MessageCreator.createMessage(info, REPLENISH_COMPLETE));
                            return;
                        }
                        for (int i = 0; i < info.size(); i++) {
                            ReplenishCommodityEntity entity = info.get(i);
                            if (entity.getFactDownAmount() > entity.getFactUpAmount()) {
                                mView.onSuccess(MessageCreator.createMessage(info.get(i), REPLENISH_COMMODITY));
                                return;
                            }
                        }
                        mView.onSuccess(MessageCreator.createMessage(info, REPLENISH_UP_COMPLETE));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    @Override
    public void loadReplenishCommodity(long replenishId, boolean isComplete) {
        Params params = Params.newInstance(Params.Type.WAREHOUSE);
        params.put("BillID", replenishId);
        params.put("QueryType", 2);

        FineExApplication.component().http()
                .loadReplenishDownCommodity(params)
                .map(new ResponseWrapper<>())
                .map(commodityEntities -> (ArrayList<ReplenishCommodityEntity>) Stream.of(commodityEntities)
                        .sortBy(ReplenishCommodityEntity::getDestPosCode)
                        .toList())
                .flatMap((Function<ArrayList<ReplenishCommodityEntity>, ObservableSource<ReplenishCommodityEntity>>) Observable::fromIterable)
                .filter(commodityEntity -> {
                    if (isComplete) {
                        return commodityEntity.isUpStatus();
                    } else {
                        return !commodityEntity.isUpStatus();
                    }
                })
                .toList()
                .toObservable()
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<List<ReplenishCommodityEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(List<ReplenishCommodityEntity> info) {
                        if (info == null || info.isEmpty()) {
                            mView.showEmpty();
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, REPLENISH_DETAIL));
                            mView.showContent();
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }


    @Override
    public void confirmReplenishUp(TaskEntity taskEntity,
                                   ReplenishBindEntity bindEntity,
                                   ReplenishCommodityEntity commodityEntity,
                                   int amount,
                                   List<BatchEntity> batchEntity) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        params.put("billID", taskEntity.getBillID());
        if (bindEntity != null && bindEntity.getContainerID() > 0)
            params.put("containerID", bindEntity.getContainerID());
        params.put("workID", taskEntity.getWorkID());
        params.put("productCategory", taskEntity.getProductCategory());
        params.put("jobStationID", taskEntity.getJobStationID());

        ArrayList<HashMap<String, Object>> maps = new ArrayList<>();
        for (int i = 0; i < batchEntity.size(); i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("stockType", commodityEntity.getStockType());
            map.put("posID", commodityEntity.getDestPosID());
            map.put("posCode", commodityEntity.getDestPosCode());
            map.put("commodityID", commodityEntity.getCommodityId());
            if (amount >= batchEntity.get(i).getAmount()) {
                map.put("amount", batchEntity.get(i).getAmount());
                amount = amount - batchEntity.get(i).getAmount();
            } else {
                map.put("amount", amount);
                amount = 0;
            }
            map.put("productBatchID", batchEntity.get(i).getProductBatchID());

            maps.add(map);
            if (amount <= 0) {
                break;
            }
        }
        params.put("commoditylst", maps);

        FineExApplication.component().http()
                .confirmReplenishUp(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Object>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Object info) {
                        mView.success("商品上架成功!");
                        mView.onSuccess(MessageCreator.createMessage(info, REPLENISH_UP));
                        loadReplenishCommodity(taskEntity.getBillID());
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }
}
